'''
https://leetcode.cn/problems/design-twitter/description/
'''
import heapq
from collections import defaultdict
from typing import List


class Twitter:

    def __init__(self):
        self.user_twitters = defaultdict(list)
        self.user_flowers = defaultdict(set)
        self.timestamp = 0

    def postTweet(self, userId: int, tweetId: int) -> None:
        twitters = self.user_twitters[userId]
        twitters.append((tweetId, self.timestamp))
        self.timestamp += 1
        if len(twitters) == 11:
            twitters.pop(0)

    def getNewsFeed(self, userId: int) -> List[int]:
        res = []
        for twitter, timestep in self.user_twitters[userId]:
            heapq.heappush(res, (timestep, twitter))
            if len(res) == 11:
                heapq.heappop(res)
        for userid in self.user_flowers[userId]:
            for twitter, timestep in self.user_twitters[userid]:
                heapq.heappush(res, (timestep, twitter))
                if len(res) == 11:
                    heapq.heappop(res)
        ans = []
        for _ in range(len(res)):
            ans.append(heapq.heappop(res)[1])
        return list(reversed(ans))

    def follow(self, followerId: int, followeeId: int) -> None:
        self.user_flowers[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.user_flowers[followerId].discard(followeeId)

